<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理 -->
      <el-row class="btn_container">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </el-row>
      <!-- 表格组件 -->
      <el-table v-loading="loading" :data="list">
        <!-- 列信息 -->
        <el-table-column align="center" label="角色" prop="name">
          <template v-slot="{row}">
            <!-- 两种场景 -->
            <!-- 编辑的状态-未编辑状态 -->
            <span v-if="!row.isEdit">{{ row.name }}</span>
            <el-input v-else v-model="row.editRow.name" size="mini" placeholder="请输入角色名称" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="启用" prop="state">
          <template v-slot="{ row }">
            <template v-if="!row.isEdit"> {{ row.state === 1 ? '已启用' : '未启用' }}</template>
            <el-switch v-else v-model="row.editRow.state" size="mini" :active-value="1" :inactive-value="0" />

          </template>
        </el-table-column>
        <el-table-column align="center" label="描述" prop="description">
          <template v-slot="{ row }">
            <span v-if="!row.isEdit">{{ row.description }}</span>
            <el-input v-else v-model="row.editRow.description" type="textarea" size="mini" :rows="3" placeholder="请输入角色描述" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="!row.isEdit">
              <el-button size="mini" type="text" @click="handleAssignPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm title="确定要删除该数据吗" @onConfirm="confirmDel(row.id)">
                <template #reference>
                  <el-button style="margin-left: 10px" size="mini" type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
            <template v-else>
              <el-button size="mini" type="primary" @click="btnEditOK(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row style="height:80px" type="flex" justify="end" align="middle">
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          layout="prev, pager, next, jumper, total"
          @current-change="changePage"
        />
      </el-row>
      <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="btnCancel">
        <!-- 表单内容 -->
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item prop="name" label="角色名称">
            <el-input v-model="roleForm.name" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item label="启用">
            <!-- 如果不需要校验 就不需要写 prop属性 -->
            <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
          </el-form-item>
          <el-form-item prop="description" label="角色描述">
            <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
                <el-button size="mini" @click="btnCancel">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <!-- 放置权限弹层 -->
    <el-dialog
      width="500px"
      title="分配权限"
      :visible.sync="showAssignDialog"
      @close="showAssignDialog = false"
    >
      <el-tree
        ref="permissionTree"
        :data="permissionTreeData"
        show-checkbox
        node-key="id"
        default-expand-all
        :props="{
          label: 'name',
          children: 'children'
        }"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnAssignRole">确定</el-button>
          <el-button size="mini" @click="showAssignDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleListAPI, addRoleAPI, updateRoleAPI, delRoleAPI, getRoleDetailAPI, assignRoleAPI } from '@/api/role'
import { transListToTreeData } from '@/utils'
import { getPermissionListAPI } from '@/api/permission'
export default {
  name: 'Role',
  data() {
    return {
      showAssignDialog: false,
      currentRoleId: null, // 记录点击角色id
      permissionTreeData: [], // 用来展示权限的数据
      showPermissionDialog: false,
      permissionData: [],
      showDialog: false,
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      list: [],
      loading: false,
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const { rows, total } = await getRoleListAPI(this.pageParams)
      this.list = rows.map(item => {
        this.$set(item, 'isEdit', false) // 使用 $set 确保响应式
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
        return item
      })
      this.pageParams.total = total
      this.loading = false
    },
    // 切换分页时 请求新的数据
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值当前页码
      this.getRoleList()
    },
    async btnOK() {
      await this.$refs.roleForm.validate()
      await addRoleAPI(this.roleForm)
      this.$message.success('新增角色成功')
      this.btnCancel()
      this.getRoleList() // 重新获取数据
    },
    btnCancel() {
      this.showDialog = false
      this.$refs.roleForm.resetFields()
    },
    // 点击编辑行
    btnEditRow(row) {
      // 将当前行的编辑状态设置为 true
      row.isEdit = true
      // 更新缓存数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 行内编辑的确定
    async  btnEditOK(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRoleAPI({
          id: row.id,
          ...row.editRow // 最新的数据
          // state: row.editRow.state,
          // name: row.editRow.name,
          // description: row.editRow.description
        })
        this.$message.success('角色更新成功') // 改的是后台更新成功
        // this.getRoleList() 不能影响其他行的数据 多行编辑 -编辑第三行 其他行全都影响了
        // row.isEdit = false
        //  { ...row.editRow, isEdit: false } => { name: '', state: 1,description: '', isEdit: false   }
        Object.assign(row, { ...row.editRow, isEdit: false })
        // Object.assign(原对象，新对象) => 把新对象合并到原对象上去
      } else {
        this.$message.warning('角色名称和描述不能为空')
      }
    },
    async confirmDel(id) {
      await delRoleAPI(id) // 删除的是后台数据
      this.$message.success('删除成功')
      if (this.list.length === 1) this.pageParams.page-- // 页码-1
      this.getRoleList()
    },
    async handleAssignPermission(id) {
      this.currentRoleId = id
      try {
        // 获取权限树数据
        const res = await getPermissionListAPI()
        this.permissionTreeData = transListToTreeData(res, 0) // 列表转化树形

        // 获取角色详情
        const roleDetail = await getRoleDetailAPI(id)
        const permIds = roleDetail.permIds || []

        // 显示弹窗并设置选中状态
        this.showAssignDialog = true // 渲染是异步的
        this.$nextTick(() => {
          this.$refs.permissionTree.setCheckedKeys(permIds) // 设置选中的key
        })
      } catch (error) {
        this.$message.error('获取权限数据失败')
      }
    },
    // 点击确定时触发
    // 给角色分配权限
    async btnAssignRole() {
      // 获取当前树组件选中的key
      await assignRoleAPI({ id: this.currentRoleId, permIds: this.$refs.permissionTree.getCheckedKeys() })
      this.showAssignDialog = false
      this.$message.success('分配权限成功')
    }
  }
}
</script>
<style scoped>
.btn_container {
  padding: 10px 20px;
}
</style>
